package jmine.tec.di.type;

import java.util.Collection;
import java.util.LinkedList;

import jmine.tec.di.cache.CachedLookupResults;
import jmine.tec.utils.register.Receiver;

/**
 * @author takeshi.fukushima
 */
public class TypeConvertionSystem extends CachedLookupResults<Class<?>, TypeConverter<?>> implements Receiver<TypeConverter<?>> {

    private final LinkedList<TypeConverter<?>> allConverters = new LinkedList<TypeConverter<?>>();

    /**
     */
    public TypeConvertionSystem() {
    }

    /**
     * @param converters os conversores de tipo
     */
    public TypeConvertionSystem(TypeConverter<?>... converters) {
        for (TypeConverter<?> typeConverter : converters) {
            this.allConverters.add(typeConverter);
        }
    }

    /**
     * @param typeConverter o {@link TypeConverter}
     * @return boolean
     */
    @Override
    public synchronized boolean doRegisterNew(TypeConverter<?> typeConverter) {
        this.allConverters.addFirst(typeConverter);
        return true;
    }

    /**
     * @param targetType o tipo alvo
     * @return {@link TypeConverter} ou null se nenhum encontrado
     */
    @Override
    public synchronized TypeConverter<?> doLookup(Class<?> targetType) {
        for (TypeConverter<?> t : this.allConverters) {
            if (t.isTypeCompatible(targetType)) {
                return t;
            }
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    public synchronized void register(Collection<? extends TypeConverter<?>> registers) {
        this.allConverters.addAll(registers);
    }

}
